package main

import (
	"flag"
	"fmt"
	"gocrypto/aes"
	"log"
	"os"
)

var (
	key     string
	content string
	h       bool
	de      bool
	en      bool
	keyLen  = 32
)

func init() {
	flag.StringVar(&content, "c", "", "the `content`")
	flag.StringVar(&key, "k", "", "the `key`")
	flag.BoolVar(&h, "h", false, "the help message")
	flag.BoolVar(&de, "d", false, "`Decrypt` the content")
	flag.BoolVar(&en, "e", false, "`Encrypt` the content")
}

func main() {
	flag.Parse()

	if h {
		flag.Usage()
		return
	}

	if content == "" {
		log.Println("content can't be empty")
		return
	}
	if key == "" {
		log.Println("key can't be empty")
		return
	}
	l := len(key)
	if l < keyLen {
		if l < keyLen {
			for i := l; i < keyLen; i++ {
				key += "a"
			}
		}
	}
	if len(key) > keyLen {
		key = key[:keyLen]
	}
	if !de && !en {
		log.Println("please choose encrypt or decrtpy")
		return
	}
	if de {
		if v, err := aes.Decrypt(content, []byte(key)); err == nil {
			fmt.Println(v)
		} else {
			log.Panicf("decrypt error: %v", err)
		}
	} else {
		if v, err := aes.Encrypt([]byte(content), []byte(key)); err == nil {
			fmt.Println(v)
		} else {
			log.Panicf("decrypt error: %v", err)
		}
	}
}

func usage() {
	fmt.Fprintf(os.Stderr, `
	gm version: gm/1.0
	Usage: gm [-h help] [-c content] [-k key] [-d decrypt] [-e encrypt]

	Options:
	`)
	flag.PrintDefaults()
}
